package co.fitstart.weapp.api.web.controller.coach;

import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.demo2do.core.entity.exception.BusinessException;
import com.demo2do.core.entity.result.HttpResult;
import com.demo2do.core.utils.DateFormatUtils;

import co.fitstart.entity.course.round.CourseRound;
import co.fitstart.entity.courseware.dietary.DietaryProgramType;
import co.fitstart.entity.courseware.fitnessgroup.BatchCourseware;
import co.fitstart.entity.principal.Principal;
import co.fitstart.weapp.api.entity.DietaryRequest;
import co.fitstart.weapp.api.entity.ExerciseRequest;
import co.fitstart.weapp.api.service.CoachService;
import co.fitstart.weapp.api.service.CourseRoundService;
import co.fitstart.weapp.api.service.CoursewareService;

/**
 * 
 * @author haiyan_xiao
 *
 */
@RestController
@RequestMapping("/coach/course-rounds/{courseRoundId}/weekly-plans")
public class WeeklyPlanController {

    private static final Logger logger = LoggerFactory.getLogger(WeeklyPlanController.class);

    @Autowired
    private CoachService coachService;

    @Autowired
    private CourseRoundService courseRoundService;

    @Autowired
    private CoursewareService coursewareService;

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @return
     */
    @RequestMapping(value = "", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult list(@RequestParam("mobile") String mobile,
                           @PathVariable("courseRoundId") Long courseRoundId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            List<BatchCourseware> batchCoursewares = coursewareService.generallyListAllWeeklyPlan(courseRound);
            
            httpResult.success().message("获取数据成功")
                                .data("weeklyPlans", batchCoursewares);
            
        } catch (Exception e) {
            logger.error("#WeeklyPlanController# list() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @param weeklyPlanId
     * @return
     */
    @RequestMapping(value = "/{weeklyPlanId}", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult view(@RequestParam("mobile") String mobile,
                           @PathVariable("courseRoundId") Long courseRoundId,
                           @PathVariable("weeklyPlanId") Long weeklyPlanId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            Principal coach = coachService.load(mobile);
            CourseRound courseRound = courseRoundService.load(courseRoundId);
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(weeklyPlanId);
            
            httpResult.success().message("获取数据成功")
                                .data("courseType", batchCourseware.getCourseRound().getCourseType())
                                .data("name", batchCourseware.getName())
                                .data("isMainCoach", coach == courseRound.getCoach())
                                .data("editStatus", batchCourseware.getEditStatus())
                                .data("dietary", coursewareService.generallyLoadDietary(batchCourseware))
                                .data("exercise", coursewareService.loadExercise(batchCourseware));
            
            if(batchCourseware.getBegin() != null && batchCourseware.getEnd() != null) {
                httpResult.data("week", DateFormatUtils.format(batchCourseware.getBegin(), "yyyy-MM-dd") + "至" + DateFormatUtils.format(batchCourseware.getEnd(), "yyyy-MM-dd"));
            }
        } catch (Exception e) {
            logger.error("#WeeklyPlanController# view() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    @RequestMapping(value = "/{weeklyPlanId}/dietary", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult viewDietary(@RequestParam("mobile") String mobile,
                                  @PathVariable("courseRoundId") Long courseRoundId,
                                  @PathVariable("weeklyPlanId") Long weeklyPlanId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(weeklyPlanId);
            
            httpResult.success().message("获取数据成功")
                                .data("name", batchCourseware.getName())
                                .data("dietary", coursewareService.generallyLoadDietary(batchCourseware))
                                .data("breakfasts", coursewareService.listDietaryTemplate(DietaryProgramType.BREAKFAST))
                                .data("lunchs", coursewareService.listDietaryTemplate(DietaryProgramType.LUNCH))
                                .data("dinners", coursewareService.listDietaryTemplate(DietaryProgramType.DINNER))
                                .data("snacks", coursewareService.listDietaryTemplate(DietaryProgramType.SNACK));
        } catch (Exception e) {
            logger.error("#WeeklyPlanController# viewDietary() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @param weeklyPlanId
     * @param dietary
     * @return
     */
    @RequestMapping(value = "/{weeklyPlanId}/edit-dietary", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult editDietary(@RequestParam("mobile") String mobile,
                                  @PathVariable("courseRoundId") Long courseRoundId,
                                  @PathVariable("weeklyPlanId") Long weeklyPlanId,
                                  @RequestBody DietaryRequest dietary) {
        HttpResult httpResult = new HttpResult();
        
        try {
            Principal coach = coachService.load(mobile);
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(weeklyPlanId);
            
            if(batchCourseware.getCourseRound().getCoach() == coach) {
                coursewareService.editDietary(batchCourseware, dietary);
                
                httpResult.success().message("编辑第" + batchCourseware.getSorting() +"周饮食成功");
            } else {
                httpResult.fail("500").message("你不是主教练,不能编辑此课程饮食");
            }
        } catch (Exception e) {
            logger.error("#WeeklyPlanController# editDietary() error", e);
            httpResult.fail("500").message("编辑饮食失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @param weeklyPlanId
     * @return
     */
    @RequestMapping(value = "/{weeklyPlanId}/exercise", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult viewExercise(@RequestParam("mobile") String mobile,
                                   @PathVariable("courseRoundId") Long courseRoundId,
                                   @PathVariable("weeklyPlanId") Long weeklyPlanId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(weeklyPlanId);
            
            httpResult.success().message("获取数据成功")
                                .data("name", batchCourseware.getName())
                                .data("exercise", coursewareService.loadExercise(batchCourseware));
        } catch (Exception e) {
            logger.error("#WeeklyPlanController# viewExercise() error", e);
            httpResult.fail("500").message("加载数据失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @param weeklyPlanId
     * @param exercise
     * @return
     */
    @RequestMapping(value = "/{weeklyPlanId}/edit-exercise", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult editExercise(@RequestParam("mobile") String mobile,
                                   @PathVariable("courseRoundId") Long courseRoundId,
                                   @PathVariable("weeklyPlanId") Long weeklyPlanId,
                                   @RequestBody ExerciseRequest exercise) {
        HttpResult httpResult = new HttpResult();
        
        try {
            if(exercise.isValid()) {
                Principal coach = coachService.load(mobile);
                BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(weeklyPlanId);
                
                if(batchCourseware.getCourseRound().getCoach() == coach) {
                    coursewareService.editExercise(batchCourseware, exercise);
                    
                    httpResult.success().message("编辑第" + batchCourseware.getSorting() +"周家庭作业成功");
                } else {
                    httpResult.fail("500").message("你不是主教练,不能编辑此课程家庭作业");
                }
            } else {
                httpResult.fail("500").message("请求参数有误");
            }
        } catch (Exception e) {
            logger.error("#WeeklyPlanController# editExercise() error", e);
            httpResult.fail("500").message("编辑家庭作业失败");
        }
        
        return httpResult;
    }

    /**
     * 
     * @param mobile
     * @param courseRoundId
     * @param weeklyPlanId
     * @return
     */
    @RequestMapping(value = "/{weeklyPlanId}/send", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE, params = "mobile")
    public HttpResult send(@RequestParam("mobile") String mobile,
                           @PathVariable("courseRoundId") Long courseRoundId,
                           @PathVariable("weeklyPlanId") Long weeklyPlanId) {
        HttpResult httpResult = new HttpResult();
        
        try {
            Principal coach = coachService.load(mobile);
            BatchCourseware batchCourseware = coursewareService.loadBatchCourseware(weeklyPlanId);
            
            if(batchCourseware.getCourseRound().getCoach() == coach) {
                coursewareService.send(batchCourseware);
                
                httpResult.success().message("发送第" + batchCourseware.getSorting() +"周课件成功");
            } else {
                httpResult.fail("500").message("你不是主教练,不能发送课件");
            }
        } catch (BusinessException e) {
            httpResult.fail("500").message(e.getMessage());
        } catch (Exception e) {
            logger.error("#WeeklyPlanController# send() error", e);
            httpResult.fail("500").message("发送课件失败");
        }
        
        return httpResult;
    }
}
